<template>
  <div class="taskDetailContent">
    <div class="detailBox">
      <div class="title">{{ currentData.title }}</div>
      <div class="date">
        <span v-if="currentData.releaseTime"
          >{{t('taskDetail', '发布时间')}} {{ currentData.releaseTime }} 
        </span>
        <span v-if="currentData.expiredTime"
          >{{t('taskDetail', '截止时间')}} {{ currentData.expiredTime }} </span
        >
      </div>
      <div class="text" v-html="renderMarkDown(currentData.describe || '')"></div>
      <div class="fileList" v-if="currentData?.files?.length">
        <div
          class="item"
          v-for="(item, index) in currentData.files"
          >
          <div class="name" @click="handleClick({ name: '下载', record: item })"><LinkOutlined />{{ item.name }}</div>
          <MinusCircleOutlined v-if="hasDel" @click="handleClick({ name: '删除', record: item, index })"/>
        </div>
      </div>
    </div>
    <div class="infoBox">
      <div class="item">
        <div class="label">{{t('taskDetail', '任务')}}</div>
        <div class="value"> {{t('taskDetail', '学习任务')}} </div>
      </div>
      <div class="item">
        <div class="label">{{t('taskDetail', '来源')}}</div>
        <div class="value">
          {{
            currentData.source == 0
              ? 'AI'
              : currentData.source == 1
              ? t('taskDetail', '教师')
              : ''
          }}
        </div>
      </div>

      <div class="item">
        <div class="label">{{t('taskDetail', '状态')}}</div>
        <div class="value">
          {{
            currentData.status
              ? currentData.status == 0
                ? t('control', '未发布')
                : currentData.status == 1
                ? t('control', '已发布')
                : currentData.status == 2
                ? t('control', '待评分')
                : t('control', '已评分')
              : ''
          }}
        </div>
      </div>
      <div class="item">
        <div class="label">{{t('taskDetail', '分值')}} / {{t('taskDetail', '最大值')}}</div>
        <div class="value">
					<span class="score">
						{{ currentData.score }}
					</span> / {{ currentData.scoreSetting }}
        </div>
      </div>
      <div class="item">
        <div class="label">{{t('taskDetail', '评分原因')}}</div>
      <div class="value" style="text-align: left;" v-html="renderMarkDown(currentData.scoreDetail || '')"></div>

      </div>
    </div>
  </div>
</template>

<script setup>
import {
  ref,
  reactive,
  defineProps,
  defineEmits,
  onMounted,
  computed,
  inject,
  watch,
} from 'vue'
import MarkdownIt from 'markdown-it'
import { LinkOutlined, MinusCircleOutlined } from '@ant-design/icons-vue'
import { learningTaskDelFile } from '@/request/stu/learnProcess'
import { message, Modal } from 'ant-design-vue'
import { t } from '@/i18n'
const { currentData, hasDel } = defineProps({
  currentData: { type: Object, default: {} },
  hasDel: { type: Boolean, default: true },
})
const renderMarkDown = (text) => {
  const md = new MarkdownIt({
    html: true,
    linkify: true,
    typographer: true,
  })
  return md.render(text.replace(t('learnProcess','推荐资料：'), `<br/>${t('learnProcess','推荐资料：')}<br/>`).replace(t('learnProcess','在线文档：'), `<br/>${t('learnProcess','在线文档：')}<br/>`)).replace('</a>', '</a><br/>').replace(/<a\s+[^>]*?(?!target=)([^>]*>)/g, function(match, p1) {
    return `<a target="_blank" ${p1}`;
  })
}
async function downloadFile(url) {
  try {
    const response = await fetch(url);
    // 获取原始文本内容
    const text = await response.text();
    
    // 创建 Blob，明确指定编码为 UTF-8
    const blob = new Blob([text], { 
      type: 'text/plain;charset=UTF-8'
    });
    
    const downloadUrl = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = downloadUrl;
    a.download = url.split('/').pop() || 'download.txt'; // 设置下载文件名
    a.style.display = 'none';
    
    document.body.appendChild(a);
    a.click();
    
    // 清理
    window.URL.revokeObjectURL(downloadUrl);
    document.body.removeChild(a);
  } catch (error) {
    console.error(t('control','下载失败:'), error);
  }
}
const emit = defineEmits()
const handleClick = async ({ name, record, index }) => {
  let req = {},
    res = null,
    operate = null
  switch (name) {
    case '下载':
    // downloadFile(record.url)
      window.open(record.url)
      break
    case '删除':
      operate = await new Promise((resolve, reject) => {
				Modal.confirm({
					content: t('control','是否确认删除'),
					onOk() {
						resolve(true);
					},
					confirmText: t('common','确定'),
					cancelText: t('common','取消'),
					onCancel() {
						resolve(false);
					},
				})
			})
			if (!operate) return
			res = await learningTaskDelFile(record.id)
			if (!res) return
			message.success(t('common','操作成功'))
      let files = [...currentData.files]
      files.splice(index, 1)
      console.log(files, { ...currentData, files })
      emit('update:currentData', { ...currentData, files })
      break
  }
}
</script>

<style lang="scss" scoped>
.taskDetailContent {
  display: flex;
  width: 100%;
  height: 100%;
  gap: 20px;
  overflow-y: auto;
  min-height: 0;
	padding: 0 20px 0 20px;
	min-height: 0;
	min-width: 0;
  .detailBox {
    flex-grow: 1;
    min-width: 400px;
    .title {
      background: #fff;
      display: flex;
      align-items: center;
      padding: 15px;
      font-size: 18px;
      font-weight: 500;
      color: #333;
      border-radius: 8px;
      box-shadow: 0px 3px 7px 0px #e3e2ff;
    }

    .date {
      margin: 16px 0;
      padding: 15px;
      background: #fff;
      border-radius: 8px;
      box-shadow: 0px 3px 7px 0px #e3e2ff;
    }

    .text {
      padding: 15px;
      background: #fff;
      border-radius: 8px;
      box-shadow: 0px 3px 7px 0px #e3e2ff;
      min-height: 200px;
			width: 100%;
			line-height: 20px;
			word-break: break-all;
    }

    .fileList {
      margin-top: 16px;
      padding: 16px 24px;
      background: #fff;
      border-radius: 6px;
      box-shadow: 0 1px 4px rgba(0, 0, 0, 0.04);

      .item {
        display: flex;
        align-items: center;
        padding: 12px 0;
        cursor: pointer;
        color: #1f2329;
        font-size: 14px;
        border-bottom: 1px solid #f2f3f5;
        .name {
          flex: 1;
          flex-wrap: wrap;
          word-break: break-all;
          &:hover {
            color: #165dff;
          }
        }
        &:last-child {
          border-bottom: none;
        }
        :deep(.anticon) {
          margin-right: 8px;
          font-size: 15px;
        }
      }
    }
  }

  .infoBox {
    min-width: 380px;
    background: #fff;
    border-radius: 6px;
    .item {
      display: flex;
      align-items: center;
      padding: 15px;
      /* box-shadow: 0 1px 4px rgba(0,0,0,0.04); */
      margin-bottom: 10px;
      background: #f7f7ff;
      border-radius: 8px;
      &:last-child {
        border-bottom: none;
      }
      .label {
        width: 120px;
        color: #776a9c;
        font-size: 14px;
      }
      .value {
        flex: 1;
        color: #1f2329;
        font-size: 14px;
        text-align: right;
				.score {
					color: #A599C5;
				}
      }
    }
  }

}
</style>
<style>
	.ant-drawer-body {
		padding: 30px 0 0 0  !important;
	}
</style>